package com.example.myapplication;

import android.content.Intent;
import android.media.AudioManager;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;


import com.example.myapplication.ocr.PictureManager;
import com.example.myapplication.samples.ColorBlobDetectionActivity;
import com.geccocrawler.gecco.GeccoEngine;

//import org.jsoup.Connection;
//import org.jsoup.Jsoup;
//import org.jsoup.nodes.Document;
//import org.jsoup.nodes.Element;
//import org.jsoup.select.Elements;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity implements AudioManager.OnAudioFocusChangeListener{
    String filePath = Environment.getExternalStorageDirectory()+"/ec/log";
    String fileName = "ec.log";
    private static final int CACHE_MAX_SIZE=5*1024*1024;// 1M
    private static final int CACHE_CLEAR_SIZE=1*1024*1024;// 1M
//    private ImageView imageView=new ImageView(MainActivity.this);
    private TestClass c=new TestClass(MainActivity.this);
    private static int method=Imgproc.TM_SQDIFF;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.e("MainApp","MainActivity onCreate ...");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//        RelativeLayout layout=(RelativeLayout) findViewById(R.id.activity_main);
//        imageView.setImageResource(R.drawable.ic_launcher);
//        layout.addView(imageView);

        android.app.FragmentManager manager=getFragmentManager();
        android.app.FragmentTransaction transaction =manager.beginTransaction();
        final TestFragment fragment1=new TestFragment();
        transaction.add(R.id.activity_main,fragment1);
        transaction.commit();

        //init();
        Button startBtn=(Button)findViewById(R.id.start_btn);
        startBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //test();
//                Intent intent = new Intent();
//                intent.setAction("net.easyconn.action.media.button");
//                KeyEvent event=new KeyEvent(KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_MEDIA_PAUSE);
//                intent.putExtra(Intent.EXTRA_KEY_EVENT,event);
//                sendBroadcast(intent);
//                android.app.FragmentManager manager=getFragmentManager();
//                android.app.FragmentTransaction transaction =manager.beginTransaction();
//                TestFragment fragment=new TestFragment();
//                transaction.replace(R.id.activity_main,fragment);
//                //transaction.remove(fragment1);
////                transaction.addToBackStack("stack");
//                transaction.commit();
//                AudioManager audioManager=(AudioManager) getSystemService(AUDIO_SERVICE);
//                audioManager.requestAudioFocus(MainActivity.this,AudioManager.STREAM_MUSIC,AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
                Algorithm algorithm=new Algorithm();
                int[] data=new int[]{3,5,9,2,13,7,32,21};
//                for(int i=0;i<data.length;i++){
//                    algorithm.createBTree(algorithm.getRootNode(),data[i]);
//                }
//
//                algorithm.traversalBTreeMiddle(algorithm.getRootNode());
//
//                algorithm.bubblingSort(data);

                algorithm.quickSort(data,0,data.length-1);

                for(int k=0;k<data.length;k++){
                    Log.e("Algorithm",""+data[k]);
                }

//                Intent intent=new Intent(MainActivity.this,ColorBlobDetectionActivity.class);
//                startActivity(intent);

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        showItemsList();
//                        getDocument();
                    }
                }).start();

            }
        });
    }

    public void showItemsList(){
//        Document document=null;
        Log.d("MainActivity","showItemsList ");
        String url="http://app1.sfda.gov.cn/datasearch/face3/search.jsp?tableId=69&bcId=124053679279972677481528707165";
        String userAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36";
        String dataDoc="";
        try {
//            Connection.Response resp = Jsoup.connect(url)
//
//                    .timeout(6000)
//
//                    .method(Connection.Method.GET)
//
//                    .maxBodySize(0)
//
//                    .followRedirects(false)
//
//                    .execute();
//
//            Map<String,String> cookies = resp.cookies();
//            String refer = resp.header("Referer");
//            Log.e("MainActivity","refer = "+refer);
//            Iterator iterator = cookies.entrySet().iterator();
//            while (iterator.hasNext()){
//                Map.Entry entry=(Map.Entry) iterator.next();
//                Log.e("MainActivity","cookie key = "+entry.getKey()+" value = "+entry.getValue());
//            }

            GeccoEngine.create()
                //工程的包路径
                .classpath("com.geccocrawler.gecco")
                //开始抓取的页面地址
                .start(url)
                //开启几个爬虫线程
                .thread(1)
                //单个爬虫每次抓取完一个请求后的间隔时间
                .interval(2000)
                //循环抓取
                .loop(true)
                //使用pc端userAgent
                .mobile(false)
                //非阻塞方式运行
                .start();

//            document = Jsoup.connect(url)
//                    .header("Host","app1.sfda.gov.cn")
//                    .header("Connection","keep-alive")
//                    //.header("Referer","http://app1.sfda.gov.cn/datasearch/face3/search.jsp?tableId=69&bcId=124053679279972677481528707165")
//                    .header("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8")
//                    .header("Accept-Encoding","gzip, deflate")
//                    .header("Accept-Language","zh-CN")
//                    .header("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36")
//                    //.cookies(cookies)
//                    //.data("tableId","69")
//                    //.data("bcId","124053679279972677481528707165")
//                    .maxBodySize(0)
//                    .timeout(100000)
//                    .get();
            //FSSBBIl1UgzbN7N82S=H52WxVF9IiJF2kDfr8X03kTjTHMh.F3NpZLD9vHlkxbt37FGMOEUC8J3TU4ol0UJ


//             dataDoc = new String(resp.bodyAsBytes());
        } catch (Exception e) {
            e.printStackTrace();
            Log.d("MainActivity","Jsoup get error "+e.getMessage());
            return;
        }

/*
        Log.d("MainActivity","document = "+(document==null?null:document.html()));
        Log.d("MainActivity","dataDoc = "+(dataDoc==null?null:dataDoc));
        //content.jsp?tableId=69&tableName=TABLE69&tableView=进口化妆品&Id=58883
        String pattern="tableId=(\\d+)&tableName=(\\w+)&tableView=[\\u4e00-\\u9fa5]+&Id=(\\d+)";
        Pattern pt=Pattern.compile(pattern,Pattern.MULTILINE);
        Matcher matcher=pt.matcher(document.html());
        while (matcher.find()){
            Log.d("MainActivity","matcher group = "+matcher.group());
        }

        if(document == null) return;
        Elements elements = document.getElementsMatchingOwnText(pt);
//        Elements elements = document.getElementsByAttributeStarting("<a href=");
        Log.d("MainActivity","elements = "+(elements==null?null:elements.size()));
        Iterator iterator=elements.iterator();
        while (iterator.hasNext()){
            Element element = (Element) iterator.next();
            String text = element.text();
            Log.d("MainActivity","element text = "+text);
        }
        */
    }

//    public static void main(String[] args) {
//        GeccoEngine.create()
//                //工程的包路径
//                .classpath("com.geccocrawler.gecco.demo")
//                //开始抓取的页面地址
//                .start("https://github.com/xtuhcy/gecco")
//                //开启几个爬虫线程
//                .thread(1)
//                //单个爬虫每次抓取完一个请求后的间隔时间
//                .interval(2000)
//                //循环抓取
//                .loop(true)
//                //使用pc端userAgent
//                .mobile(false)
//                //非阻塞方式运行
//                .start();
//    }

    public void getDocument(){
        URL url = null;
        HttpURLConnection connection=null;
        try {
            url = new URL("http://app1.sfda.gov.cn/datasearch/face3/search.jsp?tableId=69&bcId=124053679279972677481528707165");
            connection= (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection","Keep-Alive");
            connection.setReadTimeout(10*1000);
            connection.setConnectTimeout(6*1000);
            connection.setDoInput(true);
            connection.setDoOutput(true);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        int code= 0;
        try {
            code = connection.getResponseCode();
            if(code == 200 || code == 202){
                InputStream is=connection.getInputStream();
                String response= getStringFromInputStream(is);
                Log.d("MainActivity","response text = "+response);
            }else {
                Log.d("MainActivity","code text = "+code);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    private static String getStringFromInputStream(InputStream is)
            throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        // 模板代码 必须熟练
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
        }
        is.close();
        String state = os.toString();// 把流中的数据转换成字符串,采用的编码是utf-8(模拟器默认编码)
        os.close();
        return state;
    }


    public void iDentifyImage(){
        final PictureManager pictureManager=new PictureManager("");
        Mat srcImgMat = Imgcodecs.imread("/mnt/sdcard/aaa/captcha.svl");

        //图片上需要点击的字起始x,y坐标位置
        int template_start_x=58;
        int template_start_y=10;
        //图片上需要点击的所有字的长和宽
        int template_width=56;
        int template_height=18;
        //截取图片的上半部分高度
        int cut_y=36;
        Mat cutImgTop=pictureManager.cutImage(srcImgMat,new Point(template_start_x,template_start_y),template_width,template_height);
        Imgcodecs.imwrite("/mnt/sdcard/aaa/img_cut_top.jpg",cutImgTop);
        Mat cutImgBottom=pictureManager.cutImage(srcImgMat,new Point(0,cut_y),new Point(srcImgMat.cols(),srcImgMat.rows()));
        Imgcodecs.imwrite("/mnt/sdcard/aaa/img_cut_bottom.jpg",cutImgBottom);
        Mat hProjectionImg = pictureManager.horizontalProjectionCutImage(cutImgTop);
        Imgcodecs.imwrite("/mnt/sdcard/aaa/img_cut_h_projection.jpg",hProjectionImg);
        List<Mat> imgList=pictureManager.verticalProjectionCutImage(hProjectionImg,12);
        List<Point> coordinateList=new ArrayList<>();
        for(int i=0;i<imgList.size();i++){
            Imgcodecs.imwrite("/mnt/sdcard/aaa/img_cut_v_"+i+".jpg",imgList.get(i));
            Point point = pictureManager.matchImage(cutImgBottom,imgList.get(i),Imgproc.TM_SQDIFF_NORMED);
            int rows=imgList.get(i).rows();
            int cols=imgList.get(i).cols();
            Point coordinate = new Point(point.x+cols/2,point.y+cut_y+rows/2);
            coordinateList.add(coordinate);
            Log.e("MainActivity","coordinate x="+coordinate.x+" y="+coordinate.y);
        }
    }





    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return super.dispatchTouchEvent(ev);
//        FrameLayout
//        HashMap map;
//        map.entrySet();
//        map.values();
//        map.keySet()
//        HashSet
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onStart() {
        Log.e("MainApp","MainActivity onStart ...");
        super.onStart();
    }

    @Override
    public void onResume() {
        Log.e("MainApp","MainActivity onResume ..."+c.getContext().getResources());
        super.onResume();
    }

    @Override
    public void onPause() {
        Log.e("MainApp","MainActivity onPause ...");
        super.onPause();
    }

    @Override
    public void onStop() {
        Log.e("MainApp","MainActivity onStop ...");
        super.onStop();
    }
    

    @Override
    public void onDestroy() {
        Log.e("MainApp","MainActivity onDestroy ...");
        super.onDestroy();
    }

    private void init(){
        FileOutputStream outputStream=null;
        try {
            File path=new File(filePath);
            if(!path.exists()){
                path.mkdirs();
            }
            File file = new File(path,"ec.log");
            if(!file.exists()){
                file.createNewFile();
            }
            outputStream=new FileOutputStream(file);
            outputStream.write("1234567890".getBytes());
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try{
                if(outputStream!=null){
                    outputStream.close();
                }
            }catch (IOException e){
            }
        }
    }

    private void test(){
        FileChannel inChannel=null;
        FileChannel outChannel=null;
        try {
            File inFile=new File(filePath+File.separator+fileName);
            inChannel = new FileInputStream(inFile).getChannel();

            File outPath=new File(filePath);
            if(!outPath.exists()){
                outPath.mkdirs();
            }
            File outFile = new File(outPath,"temp.log");
            if(!outFile.exists()){
                outFile.createNewFile();
            }
            outChannel = new FileOutputStream(outFile).getChannel();

            //copy
            inChannel.transferTo(CACHE_CLEAR_SIZE,inChannel.size()-CACHE_CLEAR_SIZE,outChannel);

            //rename
            if(inFile.exists()){
                inFile.delete();
            }
            outFile.renameTo(inFile);

//                    MappedByteBuffer mbb= fc.map(FileChannel.MapMode.READ_WRITE,0,fc.size());
//                    MappedByteBuffer buffer = mbb.load();
//                    buffer.position(3);
//                    mbb.put(buffer);
            //mbb.clear();
//                    mbb.flip();
//                    mbb.force();
//                    byte[] array = mbb.array();
//                    fc.transferTo()
//                    fc.transferTo()
            //mbb.put("qqqqqqqq".getBytes());
            //mbb.put("".getBytes());
//                    accessFile.getFilePointer();
//                    accessFile.skipBytes(5);
//                    accessFile.setLength(10);
//                    accessFile.writeBytes("qwert");
            //accessFile.setLength(10);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(inChannel!=null){
                    inChannel.close();
                }
                if(outChannel!=null){
                    outChannel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }


    }


    @Override
    public void onAudioFocusChange(int focusChange) {
        Log.e("MainActivity","focusChange = "+focusChange);
    }
}
